<?php
namespace control;
/*
*付款申请记录类
*/

class paymentClass extends adIndexClass
{
    private const page = 'payment';
    private const table = 'payment';
    private const title = '付款申请记录';
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => L('payment.homeSearch.orderNo'),
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'stid'  => [
                        'name'  => L('payment.homeSearch.stid'),
                        'width' => 100,
                    ],
                    'deptName'         => [
                        'name'  => L('payment.homeSearch.deptName'),
                        'width' => 150,
                    ],
                    'reason'          => [
                        'name'  => L('payment.homeSearch.reason'),
                        'width' => 200,
                    ],
                    'money'          => [
                        'name'  => L('payment.homeSearch.money').'（' . static::$unit . '）',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'payType'          => [
                        'name'  => L('payment.homeSearch.payType'),
                        'width' => 120,
                    ],
                    'recordDate'          => [
                        'name'  => L('payment.homeSearch.recordDate'),
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'company'          => [
                        'name'  => L('payment.homeSearch.company'),
                        'width' => 150,
                    ],
                    'time'          => [
                        'name'  => L('payment.homeSearch.time'),
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => L('payment.homeSearch.state'),
                        'width' => 120,
                    ],
                    'isPay'          => [
                        'name'  => L('payment.homeSearch.isPay'),
                        'width' => 120,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('payment.home.orderNo') => text(array("name" => "orderNo")),
                    L('payment.home.deptName')   => text(array("name" => "deptName")),
                    L('payment.home.reason') => text(array("name" => "reason")),
                ],
                [
                    L('payment.home.company') => text(array("name" => "company")),
                    L('payment.home.moneyType')  =>  select(["name" => "moneyType", 'option' => explode('，', para('payMoneyType'))]),
                    L('payment.home.payType')  =>  select(["name" => "payType", 'option' => explode('，', para('payType'))]),
                ],
                [
                    L('payment.home.stid') => selectMultiple(["name" => "stid", 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                    L('payment.home.state') => select(array("name" => "state", "option" => $this->stateOption)),
                    L('payment.home.createTime') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>" . L('payment.homeSearch.new') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('payment.homeSearch.del') . "</span>\n";
        }
        if ($this->power(self::page, "pay")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'pay', {})\">" . L('payment.homeSearch.pay') . "</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//编号
            "reason" => $this->post('reason'),//事由
            "deptName" => $this->post('deptName'),//申请人部门
            'company' => $this->post('company')
        );
        //全等查询数组
        $equal = array(
            'moneyType' => $this->post('moneyType'),
            'payType' => $this->post('payType'),
            "stid" => $this->post('stid'),//申请人
            "state" => $this->post('state'),//状态
            "classify" => 1,
            'coid' => self::$coid
        );
        $and = $this->seeSelf(self::page);
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'));
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => L('payment.homeSearch.detail'), "click" => "newIframe('" . L('payment.homeSearch.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    case 'isPay':
                        $row[] = $this->showPayState($array['isPay']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $total = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 拨付
     * @return bool|string
     */
    public function pay()
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                L('payment.pay.tips') => L('payment.pay.tipsMsg'),
            ),
        )));
        //返回
        return $this->layer(array("title" => L('payment.pay.pay'), "height" => 160, "width" => 600, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     * 拨付编辑
     * @return bool|string
     */
    public function payEdit()
    {
        $listId = $this->post('listId');
        if (!$this->power(self::page, "pay")) {
            $json['warn'] = L('payment.payEdit.power');
        } elseif (empty($listId) || !is_array($listId)) {
            $json['warn'] = L('payment.payEdit.noChoice');
        } else {
            $x = 0;
            foreach ($listId as $id) {
                $info = query(self::table, " id = '$id'");
                if ($info['state'] == '已通过' && !$info['isPay']) {
                    $warn = update(array(
                        "table" => self::table,
                        "field" => [
                            'isPay' => 1,
                            'payStid' => self::$stid
                        ],
                        'where' => " id = '$id'"
                    ));
                    if ($warn == '更新成功') {
                        //写入到收支平衡中
                        $this->insetProfit($id);
                        $x++;
                        //添加日志
                        $text = str_replace(['{{staffName}}','{{orderNo}}'], [$this->control['name'],$info['orderNo']], L('payment.payEdit.successLog'));
                        $this->logText(["type" => self::page, "text" => $text]);
                    }
                } else {
                    $text = str_replace(['{{staffName}}','{{orderNo}}'], [$this->control['name'],$info['orderNo']], L('payment.payEdit.failLog'));
                    $this->logText(["type" => self::page, "text" => $text]);
                }

            }
            //返回
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('payment.payEdit.warn'));
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }


    /**
     * 显示拨付状态
     * @param $state
     * @return string
     */
    public function showPayState($state): string
    {
        return $state == 1 ? L('payment.showPayState.yes') : L('payment.showPayState.no');
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id')?:self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        $target = [];
        if ($info['moneyType'] == '食堂采购款') {
            $target = [
                [
                    must . L('payment.edit.hall')."：" => idSelect(array('name' => 'hallId', 'value' => $info['hallId'], 'title' => L('payment.edit.choice'), 'sqlId' => 'id', 'sqlField' => "name", 'sqlForm' => "dining_hall where state = '启用'")),
                    must . L('payment.edit.supplier')."：" => repeatSelect(array('name' => 'targetId', 'value' => $info['targetId'], 'title' => L('payment.edit.supplier'), 'sqlField' => "supplierName", 'sqlForm' => 'canteen_detail')),
                ]
            ];
        } elseif ($info['moneyType'] == '劳动报酬付款') {
            $labor_salary = query('labor_salary', "id = '$info[targetId]'");
            $target = [
                [
                    must . L('payment.edit.salaryNo')."：" => text(array('name' => 'salaryNo', 'id' => 'salaryNo', 'title' => L('payment.edit.fillSalaryNo'), 'value' => $labor_salary['orderNo'])) . hidden(array('name' => 'targetId', 'value' => $info['targetId'])) . <<<eof
<script>
$("#salaryNo").bigAutocomplete({
    url:root + 'control/adIndex.html?cla=payment&fun=getSalaryNo',
    callback:function(data,e){
       e.siblings("input[name='targetId']").val(data.id)
       $("[name='company']").val(data.companyName);
       $("[name='bankName']").val(data.companyBank);
       $("[name='bankNum']").val(data.companyBankNum);
}}) 
</script>
eof,
                ],
            ];
        }
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . L('payment.edit.reason')."：" => textarea(["name" => "reason", 'class' => 'textarea', "value" => $info['reason']]),
                ],
                [
                    must . L('payment.edit.money')."：" => text(["name" => "money", 'unit' =>  static::$unit , 'class' => 'text', "value" => $info['money']]),
                    must . L('payment.edit.moneyType')."：" => select(["name" => "moneyType", 'change' => 'showTarget', 'title' => L('payment.edit.moneyType'), 'option' => array_merge(explode('，', para('payMoneyType')), ['食堂采购款', '劳动报酬付款']), 'class' => 'text', "value" => $info['moneyType']]),
                ],
                $target,
                [
                    must . L('payment.edit.payType')."：" => select(["name" => "payType", 'title' => L('payment.edit.payType'), 'option' => explode('，', para('payType')), 'class' => 'text', "value" => $info['payType']]),
                    must . L('payment.edit.recordDate')."：" => text(["name" => "recordDate", 'laydate' => [], 'class' => 'text', "value" => $info['recordDate']]),
                ],
                [
                    must . L('payment.edit.company')."：" => text(["name" => "company", 'class' => 'text', "value" => $info['company']]),
                    must . L('payment.edit.bankName')."：" => text(["name" => "bankName", 'class' => 'text', "value" => $info['bankName']]),
                ],
                [
                    must . L('payment.edit.bankNum')."：" => text(["name" => "bankNum", 'class' => 'text', "value" => $info['bankNum']]),
                ],
                [
                    L('payment.edit.file')."：" => fileUploadClass::addFileComponent($info['id'], '付款申请', self::page, self::page . 'EditForm'),
                ],
            ],
            'hidden' => hidden(['name' => 'id', 'value' => $info['id'] ?: $id]),
        ]);
        $html .= $this->js();
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 450, "html" => $html));
    }

    public function js(): string
    {
        return <<<eof
<script>
function showTarget(e){
    let val = e.value;
    if (val==='食堂采购款' || val ==='劳动报酬付款'){
        $.post(root+'control/adIndex.html?cla=payment&fun=getTargetHtml',{type:val},function(res) {
           $(e).parent().parent().after(res.html);
        },'json')
    }
    if (val ==='食堂采购款'){
         $("[name='salaryNo']").parent().parent().remove();
    }else if(val=='劳动报酬付款'){
        $("[name='hallId']").parent().parent().remove();
    }else{
        $("[name='hallId']").parent().parent().remove();
        $("[name='salaryNo']").parent().parent().remove();
    }
}
</script>
eof;

    }

    /**
     * 获取劳动报酬编号
     * @return false|string
     */
    public function getSalaryNo(): bool|string
    {
        $val = $this->post('keyword');//关键词
        $json['data'] = [];
        $where = " and state = '已通过'";
        if ($val) {
            $where .= " and orderNo like '%$val%'";
        }

        $all = find(array('table' => 'labor_salary', 'where' => "1=1 $where order by orderNo asc limit 50"));
        foreach ($all['array'] as $array) {
            $company = query('labor_company',"id = '$array[companyId]'");
            $json['data'][] = array('title' => $array['orderNo'],'companyName'=>$company['name'],'companyBank'=>$company['companyBank'],'companyBankNum'=>$company['companyBankNum'], 'id' => $array['id']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * 获取对象HTML
     * @return bool|string
     */
    public function getTargetHtml(): bool|string
    {
        $type = $this->post('type');
        $json['html'] = '';
        if ($type == '食堂采购款') {
            $select = repeatSelect(array('name' => 'targetId', 'title' => L('payment.edit.supplier'), 'sqlField' => "supplierName", 'sqlForm' => 'canteen_detail'));
            $hallSelect = idSelect(array('name' => 'hallId', 'title' => L('payment.edit.choice'), 'sqlId' => 'id', 'sqlField' => "name", 'sqlForm' => "dining_hall where state = '启用'"));
            $hallWord = L('payment.edit.hall');
            $supplierWord = L('payment.edit.supplier');
            $json['html'] = <<<eof
<ul>
<li class="layer-line-title" title=""><span class="red">*</span>{$hallWord}：</li>
<li style="flex:1;" class="layer-line-input">{$hallSelect}</li>
<li class="layer-line-title" title=""><span class="red">*</span>{$supplierWord}：</li>
<li style="flex:1;" class="layer-line-input">{$select}</li>
</ul>
eof;

        } elseif ($type == '劳动报酬付款') {
            $select = text(array('name' => 'salaryNo', 'id' => 'salaryNo', 'title' => L('payment.edit.fillSalaryNo'))) . hidden(array('name' => 'targetId', 'value' => '')) . <<<eof
<script>
$("#salaryNo").bigAutocomplete({
    url:root + 'control/adIndex.html?cla=payment&fun=getSalaryNo',
    callback:function(data,e){
       e.siblings("input[name='targetId']").val(data.id)
       $("[name='company']").val(data.companyName);
       $("[name='bankName']").val(data.companyBank);
       $("[name='bankNum']").val(data.companyBankNum);
}}) 
</script>
eof;
            $salaryNoWord = L('payment.edit.salaryNo');
            $json['html'] = <<<eof
<ul>
<li class="layer-line-title" title=""><span class="red">*</span>{$salaryNoWord}：</li>
<li style="flex:3;" class="layer-line-input">{$select}</li>
</ul>
eof;
        }
        return json_encode($json, 320);
    }

    public function editEdit()
    {
        $fileIdArr = $this->post('fileId');
        $id = $this->post('id') ?: self::getId();
        $field = [
            'reason' => $this->post('reason'),
            'money' => $this->post('money'),
            'hallId' => $this->post('hallId'),
            'bankNum' => $this->post('bankNum'),
            'moneyType' => $this->post('moneyType'),
            'targetId' => $this->post('targetId'),
            'payType' => $this->post('payType'),
            'company' => $this->post('company'),
            'bankName' => $this->post('bankName'),
            'recordDate' => $this->post('recordDate'),
            'updateTime' => $this->time
        ];
        $annotation = [
            'reason' => L('payment.editEdit.reason'),
            'moneyType' => L('payment.editEdit.moneyType'),
            'money' => L('payment.editEdit.money'),
            'bankNum' => L('payment.editEdit.bankNum'),
            'payType' => L('payment.editEdit.payType'),
            'company' => L('payment.editEdit.company'),
            'bankName' => L('payment.editEdit.bankName'),
            'recordDate' => L('payment.editEdit.recordDate'),
        ];
        $rules = [
            'reason' => 'required',
            'moneyType' => 'required',
            'money' => 'required|numeric',
            'bankNum' => 'required',
            'payType' => 'required',
            'company' => 'required',
            'bankName' => 'required',
            'recordDate' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('payment.editEdit.power');
        } elseif ($field['moneyType'] == '食堂采购款' && empty($field['targetId'])) {
            $json['warn'] = L('payment.editEdit.choiceSupplier');
        } elseif ($field['moneyType'] == '食堂采购款' && empty($field['hallId'])) {
            $json['warn'] = L('payment.editEdit.choiceHall');
        } elseif ($field['moneyType'] == '劳动报酬付款' && empty($field['targetId'])) {
            $json['warn'] = L('payment.editEdit.choiceSalaryNo');
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'FKSQ' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $department = query('department', " id = '{$this->controlJob['departmentId']}'");
                $field = array_merge($field, [
                    'id' => $id,
                    'classify' => 1,
                    'coid' => self::$coid,
                    'deptName' => $department['name'],
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'state' => '草稿',
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加主表ID到附件表
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('payment.editEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
        if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
            $button[] = [
                "name" => L('salesContract.auditButton.start'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name' => '付款申请',
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        // 保存函数
                        'save' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'editEdit'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'finish',
                            'data' => ['id' => $info['id']]
                        ],
                    ],
                ], 320))],
            ];
        }
// 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => L('salesContract.auditButton.approval'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => L('salesContract.auditButton.addApprover'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => L('salesContract.auditButton.transfer'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];

        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿' && $info['isPay'] != 1) {
            $button[] = [
                "name" => L('salesContract.auditButton.cancel'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'cancelFun',
                            'data' => ['id' => $info['id']]
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }

    public function finish($data)
    {
        $info = query(self::table, "id = '$data[id]'");
        if ($info['moneyType'] == '劳动报酬付款') {
            $labor_salary = query('labor_salary', "id = '$info[targetId]'");
            $balance = find(array('table' => "record", 'where' => "typeId = '$labor_salary[companyId]'", 'sum' => "money"));
            insert(array(
                'table' => 'record',
                'field' => [
                    'type' => '派遣单位',
                    'typeId' => $labor_salary['companyId'],
                    'targetDate' => $info['recordDate'],
                    'classify' => '劳动报酬付款',
                    'direction' => '-',
                    'money' => $info['money'],
                    'balance' => $balance - $info['money'],
                    'orderNo' => $labor_salary['orderNo'],
                    'sourceTable' => self::table,
                    'sourceId' => $info['id'],
                    'text' => '付款申请单【' . $info['orderNo'] . '】',
                    'stName' => self::findStaff($info['stid']),
                ]
            ));
        }
    }

    public function cancelFun($data)
    {
        $info = query(self::table, "id = '$data[id]'");
        if ($info['moneyType'] == '劳动报酬付款') {
            $record = query('record', "sourceId = '$info[id]'");
            delete(array('table' => 'record', 'where' => "id = '$record[id]'"));
            self::tidyMoney($record['id'], $record['typeId'], -$record['money']);
        }
    }

    /**
     * 修改金额后要修改之后的记录
     * @param $id
     * @param $typeId
     * @param $money
     */
    public static function tidyMoney($id, $typeId, $money)
    {
        if ($money && abs($money) > 0) {
            $all = find(array('table' => 'record', 'where' => "typeId = '$typeId' and id > $id order by id asc"));
            foreach ($all['array'] as $array) {
                update(array('table' => 'record', 'field' => ['balance' => $array['balance'] + $money], 'where' => "id = '$array[id]'"));
            }
        }
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('payment.detail.empty');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => L('payment.detail.detail'),
            );

            //审核按钮
            $button = $this->auditButton($info);
            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => L('payment.detail.edit'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                ];
            }
            if ($this->power(self::page, "del") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => L('payment.detail.del'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }


            $audit = query('audit', " targetId = '$info[id]'");
            $target = '';
            if ($info['moneyType'] == '食堂采购款') {
                $target = $info['targetId'];
                $hall = query('dining_hall', "id = '$info[hallId]'");
                $target = $hall['name'] . '-' . $target;
            } elseif ($info['moneyType'] == '劳动报酬付款') {
                $labor_salary = query('labor_salary', "id = '$info[targetId]'");
                $target = $labor_salary['orderNo'];
            }
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "基本信息" => array(
                    array(
                        L('payment.detail.moneyType') => $info['moneyType'],
                        L('payment.detail.target') => $target,
                        L('payment.detail.money')."(" . static::$unit . ")" => $info['money'],
                        L('payment.detail.payType') => $info['payType'],
                    ),
                    array(

                        L('payment.detail.recordDate') => $info['recordDate'],
                        L('payment.detail.company') => $info['company'],
                        L('payment.detail.bankName') => $info['bankName'],
                        L('payment.detail.bankNum') => $info['bankNum'],
                    ),
                    array(
                        L('payment.detail.reason') => pre($info['reason']),

                    ),
                ),
                L('payment.detail.sys') => array(
                    array(
                        L('payment.detail.orderNo') => $info['orderNo'],
                        L('payment.detail.deptName') => $info['deptName'],
                        L('payment.detail.stid') => self::findStaff($info['stid']),
                        L('payment.detail.time') => $info['time'],
                    ),
                    array(
                        L('payment.detail.commitTime') => self::null($audit['commitTime']),
                        L('payment.detail.state') => $info['state'],
                    ),
                ),
                L('payment.detail.file') => array(
                    array(
                        fileUploadClass::showFile($info['id'], '付款申请')
                    )
                ),
                L('payment.detail.process') => array(
                    array(
                        auditClass::auditRecord(self::table, $info['id'])
                    )
                ),

            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('payment.operate.del');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('payment.operate.warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('payment.delete.power');
        } elseif (empty($array)) {
            $json['warn'] = L('payment.delete.noChoice');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['isPay'] == 1) {
                    //返回
                    $warn = L('payment.delete.fail');
                } elseif ($info['state'] != '草稿') {
                    $warn = L('payment.delete.stateError');
                } else {
                    $all = find(array('table' => 'file', 'where' => "targetId = '$id'"));
                    foreach ($all['array'] as $val) {
                        fileDelete($val['src']);
                        delete(array("table" => 'file', "where" => " id = '$val[id]' "));
                    }
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //删除audit表记录
                    delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message", "where" => " typeId = '$id' "));
                    //返回
                    $warn = L('payment.delete.success');
                    $x++;
                }
                $text .= str_replace(['{{id}}'], [$info['id']], L('payment.delete.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('payment.delete.log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('payment.delete.warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 拨付后写入到收支平衡表中
     */
    public function insetProfit($id)
    {
        $info = query(self::table, " id = '$id'");
        insert(array(
            'table' => 'profit',
            'field' => [
                'id' => self::getId(),
                'coid' => self::$coid,
                'stid' => $info['stid'],
                'target' => '付款申请记录',
                'targetId' => $info['id'],
                'direction' => '支出',
                'type' => '付款申请',
                'money' => $info['money'],
                'payDate' => $info['recordDate'],
                'updateTime' => $this->time,
                'time' => $this->time
            ]
        ));
    }
}

